package com.manlitech.cloudboot.config.dubboconfig;

import lombok.extern.log4j.Log4j;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.apache.dubbo.rpc.service.GenericService;

/**
 * @author shensg
 */
@Activate(group = "provider" )
@Log4j
public class DubboExceptionFilter extends ListenableFilter {

    public DubboExceptionFilter() {
        super.listener = new ExceptionListener();
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        return invoker.invoke(invocation);
    }

    static class ExceptionListener implements Listener {

        @Override
        public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {

            if (appResponse.hasException() && GenericService.class != invoker.getInterface()) {

                try {
                    Throwable exception = appResponse.getException();
                    // 内部调用不需要 , 之后需要再增加
                    /*com.manlitech.cloudboot.basebootconfig.util.Result response = null;
                    if (exception instanceof MyException){
                        MyException myException = (MyException) exception;
                        response = ResultUtil.error(myException.getCode(), myException.getMessage());
                        appResponse.setValue(response);
                        appResponse.setException(null);
                        return;
                    }else if (exception instanceof RpcException) {
                        response = ResultUtil.error(-1,exception.getMessage());
                        appResponse.setValue(response);
                        appResponse.setException(null);
                        return;
                    }else {
                        exception.printStackTrace();
                    }*/
                } catch (Throwable e) {
                    return;
                }
            }
        }

        @Override
        public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
            log.error(t.getMessage());
        }
    }
}